package gov.pbc.nn.kjgl.software.view;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.core.utils.GetTableUtils;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;
import gov.pbc.nn.kjgl.entity.Project;
import gov.pbc.nn.kjgl.maintenance.entity.SysProblem;
import gov.pbc.nn.kjgl.software.dao.KjcShDao;
import gov.pbc.nn.kjgl.software.dao.KjcShJdbcDao;
import gov.pbc.nn.kjgl.software.dao.KjkShJdbcDao;
import gov.pbc.nn.kjgl.software.dao.ProjectDao;
import gov.pbc.nn.uflo.entity.Opinion;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.uploader.UploadFile;
import com.bstek.dorado.uploader.annotation.FileResolver;
import com.bstek.uflo.client.service.ProcessClient;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.model.task.Task;
import com.bstek.uflo.service.ProcessService;
import com.bstek.uflo.service.TaskOpinion;

@Component("kjcShPR")
public class KjcShPR {

	@Autowired
	private KjcShJdbcDao kjcShJdbcDao;

	@Autowired
	private KjkShJdbcDao kjkShJdbcDao;

	@Autowired
	private KjcShDao kjcShDao;

	@Autowired
	@Qualifier(TaskClient.BEAN_ID)
	private TaskClient taskClient;

	@Autowired
	@Qualifier(ProcessClient.BEAN_ID)
	private ProcessClient processClient;

	@Autowired
	private ProcessService processService;

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao CoreHibernateDao;

	@Autowired
	private DeptService deptService;

	@Autowired
	private ProjectDao projectDao;

	@DataProvider
	public Project loadProject(String id) {
		return kjcShJdbcDao.loadProject(id);
	}

	/**
	 * 科技处同意和退回
	 * 
	 * @param taskId
	 * @param pass
	 * @param opinionText
	 * @param project
	 * @param lx
	 */

	@Transactional
	@Expose
	public void sbAction(String taskId, String pass, String opinionText, Project project) {
		Task task = taskClient.getTask(Long.valueOf(taskId));
		Map<String, Object> map = new HashMap<String, Object>();
		String dm = null;
		if (project.getDeclareMeans().equals("1")) {
			dm = "集中式立项申请";
		} else if (project.getDeclareMeans().equals("2")) {
			dm = "非集中式立项申请";
		}
		if (pass.equals("ok")) {
			map.put("agree", 1);
			map.put("taskname", dm + "【" + project.getName() + "】处领导审核通过");
		} else {
			map.put("agree", 0);
			map.put("taskname", dm + "【" + project.getName() + "】处领导审核不通过");
			this.projectDao.update(project);
		}
		final Opinion o = new Opinion();
		o.setBusKey(task.getBusinessId());
		o.setTaskId(Long.parseLong(taskId));
		o.setTaskName(task.getTaskName());
		o.setProcessName("立项申请");
		o.setBusTable("T_PROJECT");
		o.setOpinion(opinionText);
		o.setUsername(ContextHolder.getLoginUser().getUsername());
		o.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
		o.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
		o.setCname(ContextHolder.getLoginUser().getCname());
		o.setNodeName(task.getNodeName());
		this.CoreHibernateDao.save(o);
		// System.out.println(taskClient.canWithdraw(Long.valueOf(taskId)));
		taskClient.withdraw(Long.valueOf(taskId), map);
	}

	/**
	 * 上传行领导签字
	 * 
	 * @param file
	 * @param params
	 * @throws IOException
	 */
	@Transactional
	@FileResolver
	public String uploadSign(UploadFile file, Map<String, Object> params) throws IOException {
		String businessId = (String) params.get("businessId");
		Project p = projectDao.getProjectById(businessId);
		p.setZgywhldUsername((String) params.get("hldusername"));
		p.setZgywhld((String) params.get("hldname"));
		p.setHldqz(1);
		p.setYwzgDeptId((String) params.get("taskId"));
		this.projectDao.update(p);
		long taskId = Long.parseLong(params.get("taskId").toString());
		Task task = this.taskClient.getTask(taskId);
		long processInstanceId = task.getProcessInstanceId();
		ProcessInstance process = processClient.getProcessInstanceById(Long.valueOf(processInstanceId));
		// 行领导的username
		String username = (String) params.get("hldusername");
		Map<String, Object> ps = new HashMap<String, Object>();
		ps.put("taskId", taskId);
		ps.put("username", username);
		String hql = "from " + Opinion.class.getName() + " where taskId=:taskId and username=:username";
		List<Opinion> list = CoreHibernateDao.query(hql, ps);
		// 判断行领导是否有审批过，如果没有则保存，否则跟新
		if (list.isEmpty()) {
			final Opinion o = new Opinion();
			o.setBusKey(businessId);
			// o.setBusTable("");
			o.setTaskId(taskId);
			o.setBusTable(GetTableUtils.getTablename(Project.class));
			o.setCname((String) kjkShJdbcDao.getHld(username).get(0).get("Cname"));// 领导中文名
			o.setUsername(username);// 领导username
			o.setProcessName("立项申请");
			System.out.println("====" + task.getTaskName());
			o.setTaskName(task.getTaskName());
			o.setDeptId((String) kjkShJdbcDao.getHld(username).get(0).get("deptId"));// 行领导部门ID
			o.setDeptName((String) kjkShJdbcDao.getHld(username).get(0).get("name"));// 行领导部门名称
			byte[] bytes = FileCopyUtils.copyToByteArray(file.getInputStream());

			o.setOpinionImg(bytes);
			o.setNodeName(task.getNodeName());
			this.CoreHibernateDao.save(o);

			// 返回图片
			String sign = Base64.encodeBase64String(bytes);
			sign = "data:image/jpg;base64," + sign;
			return sign;
		} else {
			final Opinion o = list.get(0);
			byte[] bytes = FileCopyUtils.copyToByteArray(file.getInputStream());
			o.setOpinionImg(bytes);
			this.CoreHibernateDao.update(o);
			String sign = Base64.encodeBase64String(bytes);
			sign = "data:image/jpg;base64," + sign;
			return sign;
		}
	}

	/**
	 * 获取行领导信息
	 * 
	 * @param username
	 * @return
	 */
	@DataProvider
	public List<Map<String, Object>> getFgkjhld() {
		Dept dept = (Dept) ContextHolder.getLoginUser().getDepts().get(0);
		List<IUser> users = SecurityUtils.getUserByRoleForZZ(dept.getCDept().getId(), Constants.ROLE_HLD);
		List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
		for (IUser user : users) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("USERNAME_", user.getUsername());
			map.put("CNAME_", user.getCname());
			List<IDept> depts = deptService.loadUserDepts(user.getUsername());
			for (IDept d : depts) {
				map.put("NAME_", d.getName());
			}
			values.add(map);
		}
		return values;
	}

	/**
	 * 获取领导签字图片
	 * 
	 * @param businessId
	 * @param processInstanceId
	 * @return
	 * @throws Exception
	 */
	@Expose
	public String[] getOpinionSign(String businessId, String processInstanceId, String taskId) throws Exception {
		return this.kjcShDao.getOpinionSign(businessId, processInstanceId, taskId);
	}

}
